package com.kclm.xsap.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.kclm.xsap.dao.LoginMapper;
import com.kclm.xsap.dto.EmployeeDTO;
import com.kclm.xsap.dto.UserDTO;
import com.kclm.xsap.dto.convert.EmployeeConvert;
import com.kclm.xsap.dto.convert.UserConvert;
import com.kclm.xsap.entity.Employee;
import com.kclm.xsap.service.LoginService;
import com.kclm.xsap.vo.EmployeeVo;
import com.kclm.xsap.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author : lvhx
 * @Date: 2025/6/13 17:04
 * @Description:
 */
@Service
@Slf4j
public class LoginServiceImpl  implements LoginService {

    private LoginMapper loginMapper;
    private EmployeeConvert employeeConvert;
    private UserConvert userConvert;

    public LoginServiceImpl(LoginMapper loginMapper, EmployeeConvert employeeConvert, UserConvert userConvert) {
        this.loginMapper = loginMapper;
        this.employeeConvert = employeeConvert;
        this.userConvert = userConvert;
    }

    @Override
    public EmployeeDTO login(EmployeeVo empVO) {
        //控制层传递过来的用户名和密码
        String  name = empVO.getUsername();
        String  password = empVO.getPassword();

        //用户名和密码的有效性判断
        if(StringUtils.isBlank(name)|| StringUtils.isBlank(password)){
            log.warn("用户名或者密码为空");
            return  null;
        }
        try{
            //用户查询
            Employee employee = loginMapper.selectByNameAndPwd(name, password);
            if(employee == null){
                log.warn("用户不存在：{}",name);
                return  null;
            }
            //判断是否一有效用户 逻辑删除，1有效，0无效
            if(employee.getIsDeleted()==0){
                log.warn("无效用户：{}",name);
                return  null;
            }
            return  employeeConvert.toDTO(employee);
        }catch (Exception e){
            log.warn("登录异常",e);
            throw new RuntimeException("登录异常");
        }
    }
    //根据id 查询用户
    @Override
    public UserDTO findById(Integer id) {
       try{
           // 调用LoginMapper的根据id查询
           Employee employee =  loginMapper.selectById(id);
           if(employee == null){
               log.warn("用户不存在");
               return null;
           }
           //转为UserDTO
           return  userConvert.toDTO(employee);
       }catch (Exception e){
           log.warn("查询异常:{}",e.getMessage());
            throw  new RuntimeException("查询异常");
       }
    }

    @Override
    public int update(UserVO userVO) {
        loginMapper.update(userVO);
        return  loginMapper.update(userVO);
    }
}
